<template>
  <div class="container">
    <div v-for="(form, index) in forms" :key="index">
      <el-form
        :model="form"
        :rules="formRules"
        label-width="100px"
        :ref="`form-${index}`"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="数量" prop="count">
              <el-input-number
                v-model="form.count"
                clearable
                :controls="false"
                class="!w-1/1"
                placeholder="请输入数量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="名称" prop="name">
                <el-input clearable v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
            <el-col :span="6">
                <el-button :disabled="formLoading" type="primary" @click="handleAdd(index)">添加</el-button>
                <el-button :disabled="formLoading" v-if="index" type="danger" @click="handleDelete(index)">删除</el-button>
            </el-col>
        </el-row>
      </el-form>
    </div>
      <div v-if="!props.mode">
          <el-switch
                  v-model="state.active"
                  size="large"
                  active-text="不排序随机生成"
                  inactive-text="按顺序排序"
          />
          <el-button :disabled="formLoading" type="primary" @click="handle">生成</el-button>
          <el-button @click="exportToExcel">导出为 Excel</el-button>
      </div>
      <div v-if="!props.mode">
          <el-table :data="tableData" height="80vh">
              <!-- 添加序号列 -->
              <el-table-column type="index" label="序号" width="200"></el-table-column>
              <el-table-column v-for="item in columnData" :key="item.prop" :label="item.label" :prop="item.prop"/>
          </el-table>
      </div>
  </div>
</template>

<script setup lang="ts">
import {computed, getCurrentInstance, nextTick, ref, reactive, watch, onUnmounted, onMounted} from "vue";
import {copyValue, generateRandomCancerTypes} from "@/views/Home/index";
import XEUtils from "xe-utils";
import * as XLSX from "xlsx";
import {saveAs} from 'file-saver';
import {ElMessage} from "element-plus";

const state = reactive({
    csvValue: '',
    active: true
})

const props = defineProps({
    modelValue: {
        type: Object,
        default: {}
    },
    // 组件模式
    mode: {
        type: Boolean,
        default: false
    }
})
onMounted(() => {
    if (!props.mode) {
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Enter' || event.keyCode === 13) {
                handle()
            }
        });
    }
})
onUnmounted(() => {
    window.removeEventListener('keypress', handle);
})

const formRef = ref(); // 表单 Ref
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const tableData = ref([]);
const forms = ref([{
 name: '',
    count: 0,
},{
    name: '',
    count: 0,
}]);
watch(
    forms.value,
    (n, o) => {
        emit('update:modelValue', o)
    },
    { deep: true }
)
const emit = defineEmits(['update:modelValue'])
const formRules = reactive({
  count: [{ required: true, message: "不能为空", trigger: "blur" }],
  name: [{ required: true, message: "不能为空", trigger: "blur" }],
});
const { proxy } = getCurrentInstance()

const columnData = ref([
    {prop: 'num', label: '数量'},
]);
const handle = async () => {
// 获取所有表单的引用
    // 如果所有表单都通过校验
    if (await validate()) {
        console.log(forms.value)
        let map = forms.value.map(j => {
            return Array(j.count).fill(j.name)
        })
        let arr = []
        if (state.active) {
             arr = generateRandomCancerTypes(XEUtils.flatten(map))
        } else {
             arr = XEUtils.flatten(map)
        }
        tableData.value = arr.map(j => {
            return {
                num: j
            }
        })
        state.csvValue = arr.map(type => `${type}`).join("\n");
        copyValue(state.csvValue)
        // 可以在这里执行后续操作，例如提交数据到服务器
    } else {
        console.log('1\n' +
            '2\n' +
            '1\n' +
            '2\n' +
            '3\n' +
            '2\n')
        alert('提交失败，请检查所有表单的输入！');
    }
};
const validate = async () => {
    const formRefs = proxy.$refs;
    let allValid = true; // 用于标记所有表单是否都通过校验

    // 遍历所有表单并校验
    for (const key in formRefs) {
        if (formRefs[key][0] && formRefs[key][0]?.validate) {
            const isValid = await formRefs[key][0].validate()
            if (!isValid) {
                allValid = false; // 如果任何一个表单未通过校验，将 allValid 设置为 false
            }
        }
    }
    return allValid
}

const handleAdd = (index) => {
    forms.value.splice(index + 1, 0, {});
}
const handleDelete = (index) => {
    forms.value.splice(index,1)
}
const resetTableData = () => {
    const propToLabelMap = new Map(columnData.value.map(item => [item.prop, item.label]));
    const restructuredTableData = tableData.value.map(row => {
        const newRow = {};
        for (const prop in row) {
            if (row.hasOwnProperty(prop) && propToLabelMap.has(prop)) {
                newRow[propToLabelMap.get(prop)] = row[prop];
            }
        }
        return newRow;
    });
    return restructuredTableData;
};
const exportToExcel = () => {
    const newTableData = resetTableData();
    const worksheet = XLSX.utils.json_to_sheet(newTableData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    const excelBuffer = XLSX.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
    });
    const data = new Blob([excelBuffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    });
    saveAs(data, 'tableData.xlsx');
};
defineExpose({ validate })
</script>

<style scoped lang="scss">
.container {
  height: 100%;
  overflow-y: auto;
  background: #f7f8fa;
  margin: 10px 0;
}
</style>
